package com.xyxy.platform.modules.service.member.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xyxy.platform.modules.core.file.SystemFileService;
import com.xyxy.platform.modules.entity.content.Article;
import com.xyxy.platform.modules.entity.member.SpecificTag;
import com.xyxy.platform.modules.entity.trade.Goods;
import com.xyxy.platform.modules.repository.mybatis.member.SpecificTagMapper;
import com.xyxy.platform.modules.repository.mybatis.trade.GoodsMapper;
import com.xyxy.platform.modules.service.content.ArticleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyxy.platform.modules.core.cache.memcached.SpyMemcachedClient;
import com.xyxy.platform.modules.core.encrypt.des3.Des3;
import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.entity.IsDelete;
import com.xyxy.platform.modules.entity.common.SysArea;
import com.xyxy.platform.modules.entity.image.ImageItem;
import com.xyxy.platform.modules.entity.image.ImageTypes;
import com.xyxy.platform.modules.entity.member.Member;
import com.xyxy.platform.modules.entity.member.MemberExample;
import com.xyxy.platform.modules.repository.mybatis.member.MemberMapper;
import com.xyxy.platform.modules.service.common.address.AddressService;
import com.xyxy.platform.modules.service.image.ImageItemService;
import com.xyxy.platform.modules.service.member.MemberService;
import com.xyxy.platform.modules.service.member.vo.MemberDetail;
import com.xyxy.platform.modules.service.member.vo.SimpleMember;
import com.xyxy.platform.modules.service.sns.FollowerService;
import com.xyxy.platform.modules.service.trade.GoodsService;
import com.xyxy.platform.modules.service.trade.vo.GoodsDto;

/**
 * 简介: 会员服务
 *
 * @author Caizhenegda
 * @version 1.0
 * @Date 2015-12-21 11:39
 */
@Service
@Transactional(readOnly = false)
public class MemberServiceImpl implements MemberService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private SpyMemcachedClient memcachedClient;

    @Autowired
    private ImageItemService imageItemService;

    @Autowired
    private FollowerService followerService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private AddressService addressService;
    @Autowired
    private ArticleService articleService;

    @Autowired
    private SpecificTagMapper specificTagMapper;

    @Autowired
    private SystemFileService systemFileService;


    @Override
    @Transactional(readOnly = true)
    public Member login(String mobile, String password) throws Exception {
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            throw new Exception("手机号或密码为空, 登录失败!");
        }
        MemberExample query = new MemberExample();
        query.or().andMobileEqualTo(mobile).andPasswordEqualTo(password);
        List<Member> memberList = memberMapper.selectByExample(query);
        if (Collections3.isNotEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    @Override
    public String generateToken(Member member) {
        String token = null;
        try {
            token = Des3.encode(UUID.randomUUID() + member.getId().toString());
            // token 有效期一个月
            Integer expiredTime = 60 * 60 * 24 * 30;
            memcachedClient.set(token, expiredTime, new SimpleMember(member.getId(), member.getUserName(), token));
        } catch (Exception e) {
            logger.error("登录生成 token 失败: {}", e.getMessage());
        }
        return token;
    }

    @Override
    public SimpleMember getMemberByToken(String token) {
        if (StringUtils.isNotEmpty(token)) {
            SimpleMember simpleMember = memcachedClient.get(token);
            return simpleMember;
        }
        return null;
    }

    @Override
    public Member register(Member member) {
        Date date = new Date();
        member.setIsDel(IsDelete.NO.ordinal());
        member.setCreateTime(date);
        member.setUserName(member.getMobile());
        member.setUpdateTime(date);
        //注册，自动生成昵称
        String alias = "xyxy";
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        alias += uuid.substring(0, 10);
        member.setAlias(alias);
        memberMapper.insertSelective(member);
        return member;
    }

    @Override
    public boolean exist(String mobile) {
        MemberExample sql = new MemberExample();
        sql.or().andUserNameEqualTo(mobile);
        List<Member> memberList = memberMapper.selectByExample(sql);
        if (null == memberList || memberList.size() == 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean resetPassword(Long id, String newPassword) {
        boolean result = false;
        Member member = memberMapper.selectByPrimaryKey(id);
        if (null != member) {
            member.setPassword(newPassword);
            int rows = memberMapper.updateByPrimaryKeySelective(member);
            result = rows > 0 ? true : false;
        } else {

        }
        return result;
    }

    @Override
    public void deleteToken(String token) {
        if (StringUtils.isNotEmpty(token)) {
            memcachedClient.delete(token);
        }
    }

    @Override
    public PageInfo<MemberDetail> findRecommend(String keyword, Integer pageNum, Integer pageSize, Map<String, Object> parMap) {
        //获取第1页，10条内容，默认查询总数count
        List<MemberDetail> recommend;
        if (StringUtils.isNotEmpty(keyword)) {
            //TODO:查询开放搜索
            recommend = new ArrayList<>();
        } else {
            if (parMap == null) {
                parMap = Maps.newHashMap();
            }
            parMap.put("keyword", keyword);

            PageHelper.startPage(pageNum, pageSize, "recommend_member.idx asc");
            recommend = memberMapper.findRecommend(parMap);
            if (recommend == null) {
                recommend = new ArrayList<>();
            }
            recommend = fullMemberDetail(recommend);
        }
        return new PageInfo(recommend);
    }

    @Override
    public PageInfo findForRecommend(String keyword, Integer pageNum, Integer pageSize, Map<String, Object> parMap) {
        //获取第1页，10条内容，默认查询总数count
        List<Member> recommend = null;
        List<MemberDetail> list = null;
        PageInfo pageInfo = null;
        if (!StringUtils.isEmpty(keyword)) {
            //TODO:查询开放搜索
            recommend = new ArrayList<Member>();
        } else {
            parMap = new HashMap<String, Object>();
            parMap.put("keyword", keyword);

            PageHelper.startPage(pageNum, pageSize);
            recommend = memberMapper.findForRecommend(parMap);
            pageInfo = new PageInfo(recommend);
            if (recommend == null) {
                recommend = new ArrayList<Member>();
            } else {
                list = Lists.newArrayList();
                for (Member member : recommend) {
                    long memberId = member.getId();
                    MemberDetail memberDetail = new MemberDetail();
                    //放入用户基本信息
                    memberDetail.setMember(member);
                    //获取关注人数
                    //调用关注人数
                    Integer countFollow = followerService.countFollower(memberId);
                    memberDetail.setCountFollow(countFollow);
                    //调用是否认证
                    memberDetail.setIsAuthentication(true);
                    List<ImageItem> imageItemList = imageItemService.findImageItemList(memberId);
                    memberDetail.setImageItemList(imageItemList);
                    List<SpecificTag> specificTagByMemberId = specificTagMapper.findSpecificTagByMemberId(memberId);
                    memberDetail.setTagList(specificTagByMemberId);
                    if (member.getAddress() != null) {
                        String address = addressService.getAddressStr(Integer.parseInt(member.getAddress()), 2, "-");
                        member.setAddress(address);
                    }
                    //调用商品列表
                    List<GoodsDto> goodsDtos = goodsMapper.selectMemberGooods(memberId);
                    memberDetail.setGoods(goodsDtos);
                    list.add(memberDetail);
                }
                pageInfo.setList(list);
            }

        }
        return pageInfo;
    }

    @Override
    public PageInfo<MemberDetail> findNewest(String keyword, Integer pageNum, Integer pageSize, Map<String, Object> parMap) {
        //获取第1页，10条内容，默认查询总数count
        List<MemberDetail> recommend = null;
        if (!StringUtils.isEmpty(keyword)) {
            //TODO:查询开放搜索
            recommend = new ArrayList<MemberDetail>();
        } else {
            parMap = new HashMap<String, Object>();
            parMap.put("keyword", keyword);

            PageHelper.startPage(pageNum, pageSize, "member.update_time desc");
            recommend = memberMapper.findNewest(parMap);
            if (recommend == null) {
                recommend = new ArrayList<MemberDetail>();
            }
            recommend = fullMemberDetail(recommend);
            for (MemberDetail m : recommend) {
                Article a = articleService.selectById(m.getMember().getArticleId());
                if (a.getContent() != null) {
                    m.getMember().setArticleContent(a.getContent());
                }
            }

        }
        return new PageInfo(recommend);
    }

    @Override
    public PageInfo findForNewest(String keyword, Integer pageNum, Integer pageSize, Map<String, Object> parMap) {
        //获取第1页，10条内容，默认查询总数count
        List<Member> recommend = null;
        List<MemberDetail> list = null;
        PageInfo pageInfo = null;
        if (!StringUtils.isEmpty(keyword)) {
            //TODO:查询开放搜索
            recommend = new ArrayList<Member>();
        } else {
            if (parMap == null)
                parMap = Maps.newHashMap();
            parMap.put("keyword", keyword);
            PageHelper.startPage(pageNum, pageSize);
            recommend = memberMapper.findForNewest(parMap);
            pageInfo = new PageInfo(recommend);
            if (recommend == null) {
                recommend = new ArrayList<Member>();
            } else {
                list = Lists.newArrayList();
                for (Member member : recommend) {
                    if(member!=null) {
                        long memberId = member.getId();
                        MemberDetail memberDetail = new MemberDetail();
                        //放入用户基本信息
                        memberDetail.setMember(member);
                        //获取关注人数
                        //调用关注人数
                        Integer countFollow = followerService.countFollower(memberId);
                        memberDetail.setCountFollow(countFollow);
                        //调用是否认证
                        memberDetail.setIsAuthentication(true);
                        List<ImageItem> imageItemList = imageItemService.findImageItemList(memberId);
                        memberDetail.setImageItemList(imageItemList);
                        List<SpecificTag> specificTagByMemberId = specificTagMapper.findSpecificTagByMemberId(memberId);
                        memberDetail.setTagList(specificTagByMemberId);
                        if (StringUtils.isNotEmpty(member.getAddress())) {
                            String address = addressService.getAddressStr(Integer.parseInt(member.getAddress()), 2, "-");
                            member.setAddress(address);
                        }
                        //调用商品列表
                        List<GoodsDto> goodsDtos = goodsMapper.selectMemberGooods(memberId);
                        memberDetail.setGoods(goodsDtos);
                        list.add(memberDetail);
                    }
                }
                pageInfo.setList(list);
            }

        }
        return pageInfo;
    }

    private List<MemberDetail> fullMemberDetail(List<MemberDetail> recommend) {
        MemberDetail memberDetail = null;
        for (int i = 0; i < recommend.size(); i++) {
            memberDetail = recommend.get(i);
            //根据会员id获取关注数
            memberDetail.setCountFollow(followerService.countFollower(memberDetail.getMember().getId()));
            //根据会员id获取商品列表
            List<GoodsDto> goodsDtoList = goodsService.selectGoodsByMemberId(memberDetail.getMember().getId()).getList();
            memberDetail.setGoods(goodsDtoList);
            //处理地址
            String address = memberDetail.getMember().getAddress();
            if (!StringUtils.isEmpty(address)) {
                List<SysArea> sysAreaList = addressService.getPathArea(Integer.parseInt(address));
                memberDetail.setAddress(sysAreaList);
            }
            recommend.set(i, memberDetail);
        }
        return recommend;
    }

    @Override
    public MemberDetail findMemberDetailById(long memberId) {
        Member member = memberMapper.selectByPrimaryKey(memberId);
        if(null == member) return null;

        MemberDetail memberDetail = new MemberDetail();

        //自我介绍
        if (null != member.getArticleId()) {
            member.setArticleContent(articleService.selectById(member.getArticleId()).getContent());
        }
        //个人基本信息
        memberDetail.setMember(member);
        //根据pkgId获取头像
        Long pkgId = member.getImagePkgId();
        if (pkgId != null) {
            List<ImageItem> imageItemList = imageItemService.findImageItemList(pkgId, ImageTypes.USER_ICON);
            for(ImageItem image : imageItemList) {
                image.setUri(systemFileService.getFileUrlByUri(image.getUri()));
            }
            memberDetail.setImageItemList(imageItemList);
        }
        // 服务
        List<GoodsDto> goodsDtos = goodsMapper.selectMemberGooods(memberId);
        memberDetail.setGoods(goodsDtos);
        //个人标签
        List<SpecificTag> specificTagByMemberId = specificTagMapper.findSpecificTagByMemberId(memberId);
        memberDetail.setTagList(specificTagByMemberId);

        return memberDetail;
    }

    @Override
    public PageInfo findMemberInfoSolrj(String keyword, String pageNum, String pageSize, Map<String, Object> parMap, Integer type) {
        HttpSolrServer server = new HttpSolrServer("http://121.41.42.83:8100/solr/core1/");
        SolrQuery params = new SolrQuery();
        //个性标签ID
        Object tagId = parMap.get("categoryId");
        //是否最新推荐
        Boolean isBest = type != null && type == 1 ? false:true;
        //查询关键词
        String key = keyword==null||keyword == "" ? "*" : "*"+keyword+"*";
        params.add("q", "tagList:" + tagId + " AND isBest:" + isBest +" AND (alias:"+key+" OR tagList:"+key+")");//查询内容   *：* 查询所有的， categoryStr:x  查询 categoryStr 字段
        params.add("start", pageNum);//开始文档
        params.add("rows", pageSize);//页条数
        if(type==null||type == 2)
            params.add("sort", " createTime desc "); //设置排序
        try {
            QueryResponse rsp = server.query(params);
            SolrDocumentList docs = rsp.getResults();
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(docs.getNumFound());
            pageInfo.setList(docs);
            return pageInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Integer countHotMember() {
        Integer i = memberMapper.countRecommed();
        return i == null ? 13241 : i;
    }

    @Override
    public Integer countGoodsByMember() {
        Integer i = memberMapper.countGoodsByMember();
        return i == null ? 14215 : i;
    }

    @Override
    public boolean updateMemebrInfoById(Member member) {
        Integer i = memberMapper.updateByPrimaryKeySelective(member);
        return i > 0 ? true : false;
    }

    @Override
    public Integer countRecommedPage() {
        return memberMapper.countRecommedPage();
    }

    @Override
    public Member findById(Long memberId) {
        if (null == memberId) return null;
        return memberMapper.selectByPrimaryKey(memberId);
    }


}
